package com.jy.api.controller.admin;

import com.jy.api.controller.admin.params.MaterialAddParams;
import com.jy.api.controller.admin.params.MaterialUnitEdit;
import com.jy.api.dao.*;
import com.jy.api.domain.*;
import com.jy.api.payRes.ProductMaterialDto;
import com.jy.api.service.OpenSearchService;
import com.jy.api.util.PinYinUtil;
import com.jy.api.util.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "v1/admin/material", produces = "application/json;charset=utf-8")
public class MaterialUnitController {

    @Autowired
    private MaterialUnitDao materialUnitDao;
    @Autowired
    private ProductMaterialDao productMaterialDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private OpenSearchService openSearchService;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private ProductMaterialItemDao productMaterialItemDao;

    /**
     * 原料单位编辑/添加
     *
     * @param req
     * @return
     */
    @PostMapping(value = "unit/edit")
    public ResponseEntity unitEdit(@RequestBody MaterialUnitEdit req) {
        MaterialUnit materialUnit;
        if (req.getId() > 0) {
            materialUnit = materialUnitDao.findOne(req.getId());
            if (materialUnit == null) {
                return new ResponseEntity("原料单位不存在，请核实", HttpStatus.BAD_REQUEST);
            }
            if (!materialUnit.getName().equals(req.getName())) {
                MaterialUnit judge = materialUnitDao.findByNameAndStoreId(req.getName(), req.getStoreId());
                if (judge != null) {
                    return new ResponseEntity("原料单位已存在，请核实", HttpStatus.BAD_REQUEST);
                }
            }
        } else {
            materialUnit = new MaterialUnit();
        }
        materialUnit.setName(req.getName());
        materialUnit.setStoreId(req.getStoreId());
        materialUnitDao.save(materialUnit);
        return ResponseEntity.ok("修改/添加成功");
    }

    /**
     * 原料单位列表
     *
     * @param storeId
     * @return
     */
    @RequestMapping(value = "unit/list", method = RequestMethod.GET)
    public ResponseEntity unitList(@RequestParam(name = "storeId") String storeId, @RequestParam(name = "name", required = false, defaultValue = "") String name) {
        List<MaterialUnit> materials;
        if (StringUtils.isNotBlank(name)) {
            materials = materialUnitDao.findByNameLikeAndStoreIdOrderByIdDesc("%" + name + "%", storeId);
        } else {
            materials = materialUnitDao.findByStoreIdOrderByIdDesc(storeId);
        }
        return ResponseEntity.ok(materials);
    }

    /**
     * 原料单位删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "unit/delete", method = RequestMethod.GET)
    public ResponseEntity getConfig(@RequestParam(name = "id") int id) {
        List<ProductMaterial> productMaterial = productMaterialDao.findByUnitId(id);
        if (productMaterial.size() > 0) {
            return ResponseEntity.ok("有原料正在使用，暂无法删除");
        }
        for (ProductMaterial material : productMaterial) {
            List<Inventory> inventories = inventoryDao.findByProductIdAndEnabled(material.getId() + "", true);
            if (inventories.size() > 0) {
                return ResponseEntity.ok("该单位正在使用中，不能删除");
            }
        }
        materialUnitDao.delete(id);
        return ResponseEntity.ok("删除成功");
    }

    /**
     * 原料编辑/添加
     *
     * @param req
     * @return
     */
    @PostMapping(value = "/edit")
    public ResponseEntity materialAdd(@RequestBody MaterialAddParams req) {
        ProductMaterial material;
        if (req.getId() > 0) {
            material = productMaterialDao.findOne(req.getId());
            if (material == null) {
                return ResponseEntity.ok("原料不存在，请核实后进行编辑");
            }
            if (!material.getName().equals(req.getName())) {
                ProductMaterial judge = productMaterialDao.findByNameAndStoreId(req.getName(), req.getStoreId());
                if (judge != null) {
                    return new ResponseEntity("原料" + req.getName() + "已存在，请核实", HttpStatus.BAD_REQUEST);
                }
            }
        } else {
            material = new ProductMaterial();
        }
        material.setWarnQty(req.getWarnQty());
        material.setName(req.getName());
        material.setStoreId(req.getStoreId());
        material.setUnitId(req.getUnitId());
        material.setPy(PinYinUtil.getFirstSpell(material.getName()));

        if (req.getId() > 0) {
            List<ProductMaterialItem> items = productMaterialItemDao.findAllByProductMaterialId(req.getId());
            for (ProductMaterialItem item : items) {
                item.setProductMaterialName(material.getName());
            }
            productMaterialItemDao.save(items);

            List<Inventory> list = inventoryDao.findAllByProductIdAndMold(req.getId() + "", ProductMold.MATERIAL);
            for (Inventory inventory : list) {
                inventory.setName(material.getName());
            }
            inventoryDao.save(list);
        }


        productMaterialDao.save(material);


        return ResponseEntity.ok("添加成功");
    }


    /**
     * 原料通过名字查询列表
     *
     * @param storeId
     * @param name
     * @return
     */
    @GetMapping(value = "search/list")
    public ResponseEntity materialList(@RequestParam(name = "storeId") String storeId, @RequestParam(name = "name", required = false, defaultValue = "") String name) {
        name = name.trim();
        List<ProductMaterial> materials;
        if (StringUtils.isNotBlank(name)) {
            materials = productMaterialDao.findByNameLikeAndStoreIdOrderByUnitIdDesc("%" + name + "%", storeId);
        } else {
            materials = productMaterialDao.findByStoreIdOrderByUnitIdDesc(storeId);
        }
        return ResponseEntity.ok(materials);
    }

    @GetMapping("/query/list")
    public ResponseEntity queryList(@RequestParam(name = "storeId") String storeId, @RequestParam(name = "name") String name) {
        name = name.trim();
        List<ProductMaterial> materials;
        if (StringUtils.isBlank(name)) {
            materials = productMaterialDao.findByStoreId(storeId);
        } else {
            if (ValidatorUtil.isChinese(name)) {
                materials = productMaterialDao.findByNameLikeAndStoreId("%" + name + "%", storeId);
            } else {
                name = name.toLowerCase();
                materials = productMaterialDao.findByPyLikeAndStoreId("%" + name + "%", storeId);
            }
        }

        return ResponseEntity.ok(materials);
    }

    @GetMapping("/detail")
    public ResponseEntity detail(@RequestParam(name = "id") int id) {
        ProductMaterial material = productMaterialDao.findOne(id);
        if (material == null) {
            return ResponseEntity.badRequest().body("原料不存在，请核实");
        }
        MaterialUnit unit = materialUnitDao.findOne(material.getUnitId());
        if (unit == null) {
            return ResponseEntity.badRequest().body("单位不存在，请核实");
        }
        ProductMaterialDto productMaterialDto = new ProductMaterialDto();
        BeanUtils.copyProperties(material, productMaterialDto);
        productMaterialDto.setUnitName(unit.getName());
        return ResponseEntity.ok(productMaterialDto);
    }


    /**
     * 删除原料
     *
     * @param id
     * @param
     * @return
     */
    @GetMapping(value = "/delete")
    public ResponseEntity materialDelete(@RequestParam(name = "id") int id) {
        ProductMaterial productMaterial = productMaterialDao.findOne(id);
        if (productMaterial == null) {
            return ResponseEntity.ok("原料不存在，请核实后进行删除");
        }
        if (productMaterial.getStockQty()>0){
            return ResponseEntity.ok("原料含有库存，请核实后进行删除");
        }
        List<Inventory> inventories = inventoryDao.findByProductIdAndEnabled(id + "", true);
        for (Inventory inventory : inventories) {
            if (inventory.getQuantity()>0){
                return ResponseEntity.ok("原料含有库存，请核实后进行删除");
            }else {
                inventory.setEnabled(false);
            }
        }
        List<ProductMaterialItem> items = productMaterialItemDao.findAllByProductMaterialId(productMaterial.getId());
        for (ProductMaterialItem item : items) {
            item.setEnabled(false);
        }
        inventoryDao.save(inventories);
        productMaterialItemDao.save(items);
        productMaterialDao.delete(id);
        return ResponseEntity.ok("删除成功");
    }


}
